package icu.zhhll.local;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 非线程安全
 * 本地内存FIFO缓存
 * 队列满后，按照插入先后顺序移除缓存
 * 基于LinkedHashMap，按照插入顺序排序
 *
 * @author zh
 * @date 2023/9/8 14:46
 */
public class FIFOCache<K, V> extends LinkedHashMap<K, V> {
    private final int MAX_CACHE_SIZE;

    public FIFOCache(int cacheSize) {
        super(cacheSize, 1, false);
        MAX_CACHE_SIZE = cacheSize;
    }

    @Override
    protected boolean removeEldestEntry(Map.Entry eldest) {
        return size() > MAX_CACHE_SIZE;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<K, V> entry : entrySet()) {
            sb.append(String.format("%s:%s ", entry.getKey(), entry.getValue()));
        }
        return sb.toString();
    }
}
